package com.incar.chuxing.api;

import android.util.Log;

import com.incar.chuxing.BuildConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiStore {
    private static ApiStore instance = null;
    private static Retrofit retrofit;

    private ApiStore() {
    }

    public static ApiStore getInstance() {
        if (instance == null) {
            synchronized (ApiStore.class) {
                if (instance == null) {
                    instance = new ApiStore();
                }
            }
        }
        return instance;
    }

    public ApiService getApiService(String baseUrl) {
        return getRetrofit(baseUrl).create(ApiService.class);
    }

    public Retrofit getRetrofit(String baseUrl) {

        //配置okHttp
        OkHttpClient client;
        //JSON请求结果
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.i("OkHttpClient", "OkHttpMessage:" + message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).addInterceptor(logging).build();
        } else {
            client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).build();
        }

        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .build();

        return retrofit;
    }

    /**
     * java bean 转化json数据  序列化
     * 解析反序列化
     *
     * @return
     */
    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()//允许序列化反序列化为null
                .create();
    }

}
